package com.asialjim.wechat.apiservice.executor.handler;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * <h1><em>ASIAL JIM JAVA DOC</em></h1><hr/>
 * <h2>CLASS DESCRIPTION <i>[ NAME: InputStreamResponseHandler ]</i></h2><strong>
 * <p> 输入流响应的处理器
 * </strong><p><p><em>Copyright &copy; Asial Jim Co., LTD</em><hr/>
 *
 * @author Asial Jim &nbsp;&nbsp; <span>Email:<a href="mailto:asialjim@hotmail.com">asialjim@hotmail.com</a> &nbsp;&nbsp; <a href="asialjim@qq.com">asialjim@qq.com</a></span>
 * @version 1.0.0
 * @since 2021/3/1   &nbsp;&nbsp; JDK 8
 */
@Data
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class InputStreamResponseHandler implements ResponseHandler<InputStream> {
    private Class<? extends InputStream> returnClass;
    private static final int STATUS_CODE_300 = 300;

    @Override
    public InputStream handleResponse(final HttpResponse response) throws IOException {
        final StatusLine statusLine = response.getStatusLine();
        final HttpEntity entity = response.getEntity();
        if (statusLine.getStatusCode() >= STATUS_CODE_300){
            EntityUtils.consume(entity);
            throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());
        }
        return Objects.nonNull(entity) ? entity.getContent() : null;
    }
}